package com.phenix.mvp.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.os.Build;
import android.support.annotation.RequiresApi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**@author zhouphenix
 * 网络工具类
 */
public class NetWorkUtil {

    /**
     * 检测网络是否连接
     * @param context 上下文
     * @return boolean
     */
    public static boolean isNetConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                Network[] networks = cm.getAllNetworks();
                if (null != networks){
                    for (Network network: networks) {
                        if (cm.getNetworkInfo(network).isConnected()){
                            return true;
                        }
                    }
                }
            }
            else{
                NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
                if (null != networkInfos){
                    for (NetworkInfo info: networkInfos ) {
                        if (info.isConnected()){
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 注册接收网络连接的广播
     * @param context 上下文
     * @param receiver 动态注册广播接收器，记得注销掉
     */
    public static void registerNetworkReceiver(Context context, BroadcastReceiver receiver){
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        context.registerReceiver(receiver, intentFilter);
    }

    /**
     * app动态选择并连接一个网络连接
     * 步骤如下：
     * <p>
     * 新建一个ConnectivityManager.
     * <p>
     * 使用NetworkRequest.Builder 类创建一个NetworkRequest对象并指定你的app需要的网络特性和传输类型。
     * <p>
     * 要扫描合适的网络，请调用requestNetwork() 或者 registerNetworkCallback(), 并将NetworkRequest对象
     * 和一个ConnectivityManager.NetworkCallback作为参数传过去。如果你要在合适的网络被扫描到之后就切换到这个网络，
     * 请调用用 requestNetwork() 方法 如果仅仅接收扫描结果而不切换网络的话，请使用registerNetworkCallback() 方法.
     * 当系统探测到一个合适的网络时连接到这个网络并调用onAvailable()方法。你可以使用这个方法传进来的Network对象得到这个网络更多的信息或者使用此网络
     * @param context 上下文
     * @param callback 回调
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static void registerNetworkCallback(Context context, ConnectivityManager.NetworkCallback callback){
        NetworkRequest request = new NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
                .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .build();
        final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        manager.registerNetworkCallback(request, callback);
    }

    /**
     * 检测wifi是否连接
     * @param context 上下文
     * @return boolean
     */
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测移动网络（2G/3G/4G...）是否连接
     * @param context 上下文
     * @return boolean
     */
    public static boolean isXgConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            return networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        }
        return false;
    }

    /**
     * 判断网址是否有效
     * @param link 链接
     * @return boolean
     */
    public static boolean isLinkAvailable(String link) {
        Pattern pattern = Pattern.compile("^(http://|https://)?((?:[A-Za-z0-9]+-[A-Za-z0-9]+|[A-Za-z0-9]+)\\.)+([A-Za-z]+)[/\\?\\:]?.*$", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(link);
        return matcher.matches();
    }

}
